package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;

/**
 * 区块链配置类
 */
@Slf4j
@Configuration
public class BlockchainConfig {
    
    @Value("${fisco.bcos.cryptoMaterial.certPath}")
    private String certPath;
    
    @Value("${fisco.bcos.network.peers[0]}")
    private String peer;
    
    @Value("${fisco.bcos.cryptoMaterial.useSMCrypto}")
    private boolean useSMCrypto;

    @Value("${fisco.bcos.account.hexPrivateKey}")
    private String hexPrivateKey;
    
    /**
     * 创建FISCO BCOS客户端Bean
     * @return Client 区块链客户端
     */
    @Bean
    public Client client() {
        try {
            log.info("开始创建区块链客户端...");
            
            // 检查证书路径是否存在
            File certPathDir = new File(certPath);
            if (!certPathDir.exists() || !certPathDir.isDirectory()) {
                log.warn("证书路径不存在或不是目录: {}", certPath);
            } else {
                // 检查必要的证书文件
                checkCertificateFiles(certPathDir);
            }
            
            // 使用标准配置文件位置
            String configFile = "src/main/resources/config.yml";
            
            try {
                // 使用配置文件创建SDK
                BcosSDK sdk = BcosSDK.build(configFile);
                
                // 获取客户端
                Client client = sdk.getClient(1);
                return client;
            } catch (Exception e) {
                log.error("SDK创建失败: {}", e.getMessage(), e);
                throw new RuntimeException("SDK创建失败: " + e.getMessage(), e);
            }
        } catch (Exception e) {
            log.error("区块链客户端创建失败: {}", e.getMessage(), e);
            throw new RuntimeException("区块链客户端创建失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 检查证书文件
     * @param certPathDir 证书目录
     */
    private void checkCertificateFiles(File certPathDir) {
        String[] requiredFiles = {
                // CA证书
            "ca.crt",
                // SDK证书
            "sdk.crt",
                // SDK私钥
            "sdk.key"
        };
        
        StringBuilder missingFiles = new StringBuilder();
        
        for (String fileName : requiredFiles) {
            File file = new File(certPathDir, fileName);
            if (!file.exists() || !file.isFile()) {
                log.error("证书文件不存在: {}", file.getAbsolutePath());
                missingFiles.append(fileName).append(", ");
            }
        }
        
        if (missingFiles.length() > 0) {
            missingFiles.delete(missingFiles.length() - 2, missingFiles.length());
            throw new RuntimeException("缺少必要的证书文件: " + missingFiles.toString());
        }
    }
} 